<?php

namespace app\admin\controller;

use think\facade\Log;

class Upload
{
    /**
     * 图片上传
     * @param string $pathname
     * @return array|\think\response\Json
     */
    public static function uploadImages($pathname = 'default')
    {
        Log::write('进来了','error');

        $file = $_FILES['file']['tmp_name'];

        Log::write('请求图片上传1'.json_encode($file),'error');

        $file = self::base64EncodeImage($file);
        if (empty($file)) {
            Log::write('参数错误1：'.json_encode($file),'error');
            return json(['code' => 0, 'msg' => '参数错误1']);
        }
        $imageName = self::rands();

        Log::write('请求图片上传2','error');

        if (!preg_match('/^(data:\s*image\/(\w+);base64,)/', $file, $result)) {
            Log::write('参数错误2：'.json_encode($result),'error');
            return ['code' => 0, 'msg' => '参数错误2'];
        }

        Log::write('请求图片上传3'.json_encode($result),'error');

        //获取图片后缀
        $type = $result[2];

        $new_file = "/public/" . $pathname . "Image/" . date('Ymd', time()) . "/";
        $new_file2 = "/public/" . $pathname . "Image/" . date('Ymd', time()) . "/";
        $fullpath = $_SERVER['DOCUMENT_ROOT'] . $new_file;
        if (!file_exists($fullpath)) {
            @mkdir($fullpath, 0775, true);
        }
        Log::write('请求图片上传4'.json_encode($fullpath),'error');

        $fullpath = $fullpath . $imageName . ".{$type}";
        $new_file = $new_file . $imageName . ".{$type}";

        if (!file_put_contents($fullpath, base64_decode(str_replace($result[1], '', $file)))) {
            Log::write('图片生成失败：'.json_encode($fullpath),'error');
            return ['code' => 0, 'msg' => '图片生成失败'];
        }

        $source = $_SERVER['DOCUMENT_ROOT'] . $new_file2 . $imageName . ".{$type}";//原图文件名
        $percent = 1;  #原图压缩，不缩放，但体积大大降低
        (new \upload\Upload($source, $percent))->compressImg($source);

        Log::write('结束了','error');

        Log::write('图片上传成功路径：'.json_encode($new_file),'error');

        return json(['code' => 1, 'msg' => 'success', 'data' => ['src' => $new_file]]);
    }

    /**
     * 图片转base64
     * @param $image_file
     * @return string
     */
    private static function base64EncodeImage($image_file)
    {
        $base64_image = '';
        $image_info = getimagesize($image_file);
        $image_data = fread(fopen($image_file, 'r'), filesize($image_file));
        $base64_image = 'data:' . $image_info['mime'] . ';base64,' . chunk_split(base64_encode($image_data));
        return $base64_image;
    }

    /**
     * 拼接随机字符
     * @return string
     */
    private static function rands()
    {
        return md5(date("His", time()) . "_" . rand(1111, 9999));
    }


    /**
     * 视频上传
     * @param $file
     * @param string $path
     * @return \think\response\Json
     */
    public static function uploadVideo($file, $path = 'default')
    {
        // 获取文件类型
        $ext = strtolower(pathinfo(@$file['name'], PATHINFO_EXTENSION));
        $date = '/public/' . $path . 'Video/' . date('Ymd');
        $fullpath = $_SERVER['DOCUMENT_ROOT'] . $date;
        // 目录是否存在
        if (!file_exists($fullpath)) {
            @mkdir($fullpath, 0775, true);
        }
        // 生成唯一的文件名
        $fileName = md5(date('Ymd') . time()) . '.' . $ext;
        // 将文件名拼接到指定的目录下
        $destName = $fullpath . "/" . $fileName;
        // 进行文件移动
        if (!move_uploaded_file($file['tmp_name'], $destName)) {
            return json(['code' => 0, 'msg' => 'error', 'data' => '上传失败']);
        }

        Log::write('视频上传成功路径：'.json_encode($fileName));
        return json(['code' => 1, 'msg' => 'success', 'data' => $date . '/' . $fileName]);
    }

    /**
     * 图片/视频删除
     * @param $path
     * @return \think\response\Json
     */
    public static function delImageOrVideo($path)
    {
        $filePath = $_SERVER['DOCUMENT_ROOT'] . $path;
        Log::write('删除的路径是：' . $filePath, 'error');
        if (file_exists($filePath)) {
            unlink($filePath);
            return json(['code' => 1, 'msg' => 'success']);
        } else {
            return json(['code' => 0, 'msg' => '找不到该文件']);
        }
    }
}